package com.zx.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.ruiji.common.R;
import com.zx.ruiji.dto.SetmealDto;
import com.zx.ruiji.entity.Category;
import com.zx.ruiji.entity.Dish;
import com.zx.ruiji.entity.Setmeal;
import com.zx.ruiji.entity.SetmealDish;
import com.zx.ruiji.service.CategoryService;
import com.zx.ruiji.service.DishService;
import com.zx.ruiji.service.SetmealDishService;
import com.zx.ruiji.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")

@Slf4j
public class SetmealController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;


    /**
     * 新增
     *
     * @param setmealDto
     * @return
     */
    //CacheEvict清除setmealCache名称下，所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return R.success("新增成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
//        分页构造器
        Page<Setmeal> pageInfo = new Page(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page(page, pageSize);
//        条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
//        分页页面展示形式
        queryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
//        分页查询
        setmealService.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }


    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    //CacheEvict清除setmealCache名称下，所有的缓存数据
    @CacheEvict(value = "setmealCache", allEntries = true)
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("要删除的套餐：{}", ids);

        setmealService.deleteById(ids);
        return R.success("null");
    }

    /**
     * 套餐修改
     *
     * @param id
     * @return
     */
//    @CacheEvict(value = "setmealCache", allEntries = true)
    @GetMapping("/{id}")
    public R update(@PathVariable Long id) {
        //获取数据
        log.info("查询到的内容是：{}", id);
        Setmeal setmeal = setmealService.getById(id);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(wrapper);

        //把基本属性添加到Dto集合中
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);


        //把菜品添加到套餐分类中
        setmealDto.setSetmealDishes(list);

//        SetmealDto dto = new SetmealDto();
//        //拷贝基本参数


        return R.success(setmealDto);
    }

    /**
     * 保存套餐的修改
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PutMapping
    public R SaveThePackage(@RequestBody SetmealDto setmealDto) {
        log.info("收集到的套餐数据是：{}", setmealDto);
        //1.修改套餐基本数据
        setmealService.updateById(setmealDto);

        List<SetmealDish> dishList = setmealDto.getSetmealDishes();

        //删除套餐内的所有菜品
        //delete from setmealDishes where setmeal_dish = ?
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmealDto.getId() != null, SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(wrapper);

        //把每一个菜品重新添加到数据库
//        dishList.stream().map(item->{
        //insert into ...where setmealDto.getId = SetmealDish::getSetmealId
        List<SetmealDish> list = dishList.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);

        return R.success("修改成功");
    }


    /**
     * 套餐批量起售，停售
     *
     * @param id
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PostMapping("/status/{id}")
    public R Batch(@PathVariable Integer id, @RequestParam List<Long> ids) {
        //根据id查询出所有选择的套餐

        List<Setmeal> setmeals = setmealService.listByIds(ids);

        List<Setmeal> list = setmeals.stream().map(item -> {
            item.setStatus(id);
            setmealService.updateById(item);
            return item;
        }).collect(Collectors.toList());

        return R.success(list);

    }

    /**
     * 回显套餐内容
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R list(Setmeal setmeal) {
        //获取参数
        log.info("套餐的id为：{}", setmeal);
        //条件查询
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        wrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        //查询
        List<Setmeal> list = setmealService.list(wrapper);

        return R.success(list);
    }


    /**
     * 菜品，套餐，点击显示
     *
     * @return id = 套餐的id
     */
    @GetMapping("/dish/{id}")
    public R dish(@PathVariable Long id) {
        //1.获取参数
        log.info("菜品id为：{}", id);


        //2.查询套餐内容
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        //找到套菜对应的菜品
        wrapper.eq(id != null, SetmealDish::getSetmealId, id);
        //3.获取套餐菜品的对象
        List<SetmealDish> list = setmealDishService.list(wrapper);

        //4.图片解决
        list = list.stream().map(item -> {
            //item:每个菜品
            Dish dish = dishService.getById(item.getDishId());
            BeanUtils.copyProperties(dish, item);
            return item;
        }).collect(Collectors.toList());


        return R.success(list);
    }


}
